import React from 'react';
import { useEffect, useState, useMemo, useContext } from 'react';
import Image from 'next/image';
import { useTranslation } from 'react-i18next';
import { Button, Input, Select, Tree, Card, Checkbox } from 'antd';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import WorkbenchesIcon from '@/components/workbenches/icons';
import MyEmpty from '@/components/common/MyEmpty';
import { dataTypeEnum, DimensionMeasurementEnum, getMetricsOptionsChange, } from '@/components/workbenches/hooks/type';
const filterTreeData = (data: any[], value: string) => {
  return data.filter((node) => {
    const str = typeof node.title == 'string' && node.title.includes(value);
    const components = node?.label?.includes(value);
    if (str || components) {
      return true;
    } else if (node.children && node.children.length > 0) {
      node.children = filterTreeData(node.children, value);
      return node.children.length > 0;
    } else {
      return false;
    }
  });
};
// 统计粒度 Y:年 M:月 D:日
// 聚合方式 SUM:求和 COUNT:计数 AVG:平均 MAX:最大值 MIN:最小值
enum InitTreeKeyType {
  TJLD0 = 'tjld-D',
  TJLD1 = 'tjld-M',
  TJLD2 = 'tjld-Y',
  JHFS0 = 'jhfs-SUM',
  JHFS1 = 'jhfs-COUNT',
  JHFS2 = 'jhfs-AVG',
  JHFS3 = 'jhfs-MAX',
  JHFS4 = 'jhfs-MIN',
}

const DataCard: React.FC<{
  currentItem: any;
  nodeData: any[];
  checkedState: any
  handleCheckboxChange: (key: string, isChecked: boolean) => void
}> = ({ currentItem, nodeData, checkedState, handleCheckboxChange }) => {
  const { t, i18n } = useTranslation();
  const InitOptions = [
    {

      label: '统计粒度',
      title: '统计粒度',
      key: 'time',
      icon: <WorkbenchesIcon type='统计粒度' />,
      children: [
        {

          label: '日',
          title:
            <div className='flex items-center'>
              <WorkbenchesIcon type='统计粒度' />
              <Checkbox
                checked={checkedState[InitTreeKeyType.TJLD0]} className='ml-1' onChange={(e) => handleCheckboxChange(InitTreeKeyType.TJLD0, e.target.checked)}>日</Checkbox>
            </div>,
          key: InitTreeKeyType.TJLD0,
        },
        {

          label: '月',
          title:
            <div className='flex items-center'>
              <WorkbenchesIcon type='统计粒度' />
              <Checkbox checked={checkedState[InitTreeKeyType.TJLD1]} className='ml-1' onChange={(e) => handleCheckboxChange(InitTreeKeyType.TJLD1, e.target.checked)}>月</Checkbox>
            </div>,
          key: InitTreeKeyType.TJLD1,
        },
        {

          label: '年',
          title:
            <div className='flex items-center'>
              <WorkbenchesIcon type='统计粒度' />
              <Checkbox checked={checkedState[InitTreeKeyType.TJLD2]} className='ml-1' onChange={(e) => handleCheckboxChange(InitTreeKeyType.TJLD2, e.target.checked)}>年</Checkbox>
            </div>,
          key: InitTreeKeyType.TJLD2,
        },
      ]
    },
    {

      label: '聚合方式',
      title: '聚合方式',
      key: 'jhfs',
      icon: <WorkbenchesIcon type='聚合方式' />,
      children: [
        {
          label: '求和',
          title:
            <div className='flex items-center'>
              <WorkbenchesIcon type='聚合方式' />
              <Checkbox checked={checkedState[InitTreeKeyType.JHFS0]} className='ml-1' onChange={(e) => handleCheckboxChange(InitTreeKeyType.JHFS0, e.target.checked)}>求和</Checkbox>
            </div>,
          key: InitTreeKeyType.JHFS0,
        },
        {
          label: '计数',
          title:
            <div className='flex items-center'>
              <WorkbenchesIcon type='聚合方式' />
              <Checkbox checked={checkedState[InitTreeKeyType.JHFS1]} className='ml-1' onChange={(e) => handleCheckboxChange(InitTreeKeyType.JHFS1, e.target.checked)}>计数</Checkbox>
            </div>,
          key: InitTreeKeyType.JHFS1,
        },
        {
          label: '平均',
          title:
            <div className='flex items-center'>
              <WorkbenchesIcon type='聚合方式' />
              <Checkbox checked={checkedState[InitTreeKeyType.JHFS2]} className='ml-1' onChange={(e) => handleCheckboxChange(InitTreeKeyType.JHFS2, e.target.checked)}>平均</Checkbox>
            </div>,
          key: InitTreeKeyType.JHFS2,
        },
        {
          label: '最大值',
          title:
            <div className='flex items-center'>
              <WorkbenchesIcon type='聚合方式' />
              <Checkbox checked={checkedState[InitTreeKeyType.JHFS3]} className='ml-1' onChange={(e) => handleCheckboxChange(InitTreeKeyType.JHFS3, e.target.checked)}>最大值</Checkbox>
            </div>,
          key: InitTreeKeyType.JHFS3,
        },
        {
          label: '最小值',
          title:
            <div className='flex items-center'>
              <WorkbenchesIcon type='聚合方式' />
              <Checkbox checked={checkedState[InitTreeKeyType.JHFS4]} className='ml-1' onChange={(e) => handleCheckboxChange(InitTreeKeyType.JHFS4, e.target.checked)}>最小值</Checkbox>
            </div>,
          key: InitTreeKeyType.JHFS4,
        },
      ]
    },
  ]

  const [treeData, setTreeData] = useState([] as any[]);

  const [searchValue, setSearchValue] = useState('');
  useEffect(() => {
    let dataList = [];
    for (const i of nodeData) {
      if (i.dataList?.length) {
        dataList.push(...i.dataList);
      }
    }
    let attributeObj: any = {
      dimension: [],
      measurement: [],
      timeDimension: [],
    }
    if (dataList.length) {
      attributeObj.dimension = dataList.filter(i => i.metrics == DimensionMeasurementEnum.Dimension).map((item: any, index: number) => {
        return {
          ...item,
          title: item.field,
          key: `dimension-${index}`,
          icon: <WorkbenchesIcon type='模型指标_维度' />,
        }
      })
      attributeObj.measurement = dataList.filter(i => i.metrics == DimensionMeasurementEnum.Measurement).map((item: any, index: number) => {
        return {
          ...item,
          title: item.field,
          key: `measurement-${index}`,
          icon: <WorkbenchesIcon type='模型指标_度量' />,
        }
      })

      attributeObj.timeDimension = dataList.filter(i => 'isTimeDimension' in i && i.isTimeDimension).map((item: any, index: number) => {
        return {
          ...item,
          title: item.field,
          key: `timeDimension-${index}`,
          icon: <WorkbenchesIcon type='模型指标_时间维度' />,
        }
      })
    }
    setTreeData([
      {

        title: '数据结构',
        key: '0',
        icon: <WorkbenchesIcon type='模型' />,
        children: nodeData.map((item: any, index: number) => {
          return {
            tableType: item.tableType,
            describe: item.describe,
            title: item.tableName || item.describe,
            key: `MX-${index}`,
            icon: <WorkbenchesIcon type={`${item.tableType == 0 ? '表' : '查询'}`} />,
          }
        })
      },
      {

        title: '属性',
        key: '1',
        icon: <WorkbenchesIcon type='属性' />,
        children: [
          {
            title: '维度',
            key: '2',
            children: attributeObj.dimension
          },
          {

            title: '度量',
            key: '3',
            children: attributeObj.measurement
          },
          {
            title: '时间维度',
            key: '4',
            children: attributeObj.timeDimension
          },
        ]
      },

      ...InitOptions,
    ])
    // console.log('checkedS232323tate', nodeData, currentItem, checkedState)
  }, [nodeData, searchValue, checkedState, currentItem])
  const [isDataCard, setIsDataCard] = useState(true);
  const [showButton, setShowButton] = useState(false);
  useEffect(() => {
    if (!isDataCard) {
      const timeoutId = setTimeout(() => {
        setShowButton(true);
      }, 1000);
      return () => clearTimeout(timeoutId);
    } else {
      setShowButton(false);
    }
  }, [isDataCard]);

  const filteredTree = useMemo(() => {
    return filterTreeData(treeData, searchValue);
  }, [searchValue, treeData,]);
  return <>
    <Card className={`absolute top-14 ${isDataCard ? 'left-0' : 'left-[-300px]'}
      transition-all duration-1000 ease-in-out w-60 z-10 overflow-y-auto`}
      style={{ width: 300, height: 'calc(100% - 40px)' }} size="small" title={
        <div className='flex items-center justify-between py-2'>
          <Input value={searchValue} onChange={(e: any) => {
            setSearchValue(e.target.value)
          }} allowClear className='w-44' defaultValue="" />
          <div onClick={() => setIsDataCard(!isDataCard)} className='cursor-pointer'>
            {
              isDataCard ?
                <WorkbenchesIcon type='收起' /> :
                <WorkbenchesIcon type='展开' />
            }
          </div>
        </div>
      }>

      {
        !filteredTree?.length ? <MyEmpty className='mt-48' description='无数据' /> :
          <Tree
            className='w-full h-full py-2'
            showIcon
            defaultExpandAll
            treeData={filteredTree}
          />
      }
    </Card>
    {showButton && (
      <Button
        className="absolute top-14 left-0 z-20 dark:border-btnDarkBorder"
        onClick={() => setIsDataCard(true)}
      >
        <WorkbenchesIcon type='展开' />
      </Button>
    )}
  </>
}
export default DataCard;